﻿using System;
using System.Web;
using System.Web.Caching;
using System.IO;
using LMD.Constant;

/// <summary>
/// Summary description for CacheRemoval
/// </summary>
public static class CacheDependencyManager
{
    public static CacheDependency CreateDependencyFile(String sxDependencyName)
    {
        return CreateDependencyFile(sxDependencyName, String.Empty);
    }
    public static CacheDependency CreateDependencyFile(String sxDependencyName, String sxIdentifier)
    {
        String sxFilename = String.Format(KCache.Filename.DIRECTORY, sxDependencyName);
        String sxFullname = HttpRuntime.AppDomainAppPath + sxFilename;
        FileInfo fi = new FileInfo(sxFullname);

        String sxCacheFile = sxFullname;

        if( !String.IsNullOrEmpty(sxIdentifier))
        {
            String sxNameOnly = fi.FullName.Remove(fi.FullName.Length - fi.Extension.Length);
            String sxExtension = fi.Extension;

            sxCacheFile = sxNameOnly + "_" + sxIdentifier + sxExtension;
        }

        FileInfo ficache = new FileInfo(sxCacheFile);

        if (!ficache.Exists)
        {
            ficache.Create();
        }

        return new CacheDependency(ficache.FullName);
    }

    public static void RemoveCache(String sxFileDependency)
    { 
        //String sxFullname = HttpContext.Current.Server.MapPath(sxFileDependency);
        //String sxFullname = HttpRuntime.AppDomainAppPath + sxFileDependency;

        String sxFilename = String.Format(KCache.Filename.DIRECTORY, sxFileDependency);
        String sxFullname = HttpRuntime.AppDomainAppPath + sxFilename;

        FileInfo fi = new FileInfo(sxFullname);
        StreamWriter writer = fi.AppendText();
        
        try
        {
            writer.WriteLine("refreshed at " + DateTime.Now.ToString());
            writer.Flush();
        }
        finally
        {
            writer.Close();
        }
    }    
}
